import options from './utils/options.js';
import { showNotification } from './utils/notification.js';
import { get as i18nGet, replace as i18nReplace } from './utils/i18n.js';
import { syncTimer } from './utils/syncTimer.js';

function setOptions (options = {}) {
  const opts = Object.assign({}, options);
  let inputs = document.querySelectorAll('#options-wrapper input');
  inputs = Array.from(inputs || []);
  inputs.forEach(input => {
    if (input.type === 'radio') {
      input.checked = input.value === opts[input.name];
      return;
    }
    input.value = opts[input.name] || '';
  });

  // 显示/隐藏自定义同步间隔
  const customSyncInterval = document.getElementById('custom_sync_interval');
  const autoSyncRadios = document.querySelectorAll('input[name="auto_sync"]');
  autoSyncRadios.forEach(radio => {
    if (radio.checked && radio.value === 'custom') {
      customSyncInterval.style.display = 'block';
    }
  });
}

// 添加事件监听，显示/隐藏自定义同步间隔
function setupEventListeners() {
  const autoSyncRadios = document.querySelectorAll('input[name="auto_sync"]');
  const customSyncInterval = document.getElementById('custom_sync_interval');

  autoSyncRadios.forEach(radio => {
    radio.addEventListener('change', function() {
      if (this.value === 'custom') {
        customSyncInterval.style.display = 'block';
      } else {
        customSyncInterval.style.display = 'none';
      }
    });
  });
}

// 在页面加载完成后设置事件监听
document.addEventListener('DOMContentLoaded', setupEventListeners);
async function updateOptions (opts) {
  await options.update(opts);
  showNotification(i18nGet('OPTIONS_UPDATED'));
}

function save() {
  const form = document.getElementById('options-wrapper');
  const formData = new FormData(form);
  const entries = formData.entries();
  let emptyField = '';
  const options = Array.from(entries).reduce((acc, [name, value]) => {
    if (!value && name !== 'sync_interval') { // sync_interval 可能为空
      emptyField = name;
      return acc;
    }
    acc[name] = value;
    return acc;
  }, {});

  if (emptyField) {
    window.alert(`${i18nGet('CHECK_INPUT')}: ${emptyField}`);
    return;
  }

  // 保存定时同步配置
  const autoSyncConfig = {
    enabled: options.auto_sync !== 'disabled',
    frequency: options.auto_sync,
    interval: options.sync_interval || '60'
  };

  syncTimer.saveConfig(autoSyncConfig);
  updateOptions(options);
}

window.addEventListener('click', e => {
  if (e.target && e.target.className === 'save-btn') {
    save();
  }
});

i18nReplace();

(async function () {
  try {
    await options.fetch();
    setOptions(options.options);
  } catch (e) {
    window.alert(e.message);
  }
})();